package com.sfx.concurrent.demo.JVM.heap;

import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

public class softReference {

    public static void main1(String[] args) {
        byte[] bytes = new byte[1024 * 1024 * 100];
        SoftReference<byte[]> softReference = new SoftReference<byte[]>(bytes);
        // 强引用去除掉
        bytes = null;
        // 得到软引用中的对象
        System.out.println(softReference.get());
        // 再去创建一个对象
        bytes = new byte[1024 * 1024 * 100];
        System.out.println(softReference.get());


        bytes = new byte[1024 * 1024 * 100];
    }

    public static void main2(String[] args) {
        ReferenceQueue<byte[]> queue = new ReferenceQueue<byte[]>();
        List<SoftReference<byte[]>> softReferences = new ArrayList<>();
        for (int i = 0; i < 10; ++i) {
            byte[] bytes = new byte[1024 * 1024 * 100];
            SoftReference<byte[]> softReference = new SoftReference<byte[]>(bytes, queue);
            softReferences.add(softReference);
        }
        SoftReference<byte[]> ref = null;
        int count = 0;
        while ((ref = (SoftReference<byte[]>) queue.poll()) != null) {
            count++;
        }
        System.out.println(count);
    }


    public static void main3(String[] args) {
        byte[] bytes = new byte[1024 * 1024 * 100];
        WeakReference<byte[]> weakReference = new WeakReference<byte[]>(bytes);
        // 强引用去除掉
        bytes = null;
        // 得到软引用中的对象
        System.out.println(weakReference.get());

        System.gc();
        bytes = new byte[1024 * 1024 * 100];

        System.out.println(weakReference.get());
    }
}